package main

import (
	"encoding/binary"
	"fmt"
	"time"

	"go-tuplestore/tuplestore"
)

func main() {
	// 创建配置
	config := tuplestore.Config{
		MergeThreshold:   100,
		MaxDeltaSize:     1024 * 1024, // 1MB
		MaxMergeInterval: time.Hour,
		InitialSegments:  4,
		BlocksPerSegment: 10,
	}

	// 定义元组数据格式
	schema := []tuplestore.ElementInfo{
		{Type: tuplestore.TypeString, Offset: 0, Size: 50, Nullable: false},  // ID
		{Type: tuplestore.TypeInt32, Offset: 50, Size: 4, Nullable: false},   // Age
		{Type: tuplestore.TypeString, Offset: 54, Size: 100, Nullable: true}, // Name
		{Type: tuplestore.TypeTime, Offset: 154, Size: 8, Nullable: false},   // CreatedAt
	}

	// 初始化 TupleStore
	store := tuplestore.NewTupleStore(config)

	// 创建测试元组
	createTuple := func(id string, age int32, name string) *tuplestore.Tuple {
		data := make([]byte, 162) // 总大小：50 + 4 + 100 + 8
		copy(data[0:50], []byte(id))
		binary.LittleEndian.PutUint32(data[50:54], uint32(age))
		copy(data[54:154], []byte(name))
		binary.LittleEndian.PutUint64(data[154:162], uint64(time.Now().UnixNano()))

		return &tuplestore.Tuple{
			ID:        id,
			Data:      data,
			Timestamp: time.Now(),
			Schema:    schema,
		}
	}

	// 准备测试数据
	tuples := []*tuplestore.Tuple{
		createTuple("user1", 25, "Alice"),
		createTuple("user2", 30, "Bob"),
		createTuple("user3", 35, "Charlie"),
		createTuple("user4", 25, "David"),
	}

	// 批量插入
	if err := store.BatchInsert(tuples); err != nil {
		fmt.Printf("批量插入失败: %v\n", err)
		return
	}
	fmt.Println("批量插入成功")

	// 测试ID查询
	tuple, err := store.GetByID("user1")
	if err != nil {
		fmt.Printf("ID查询失败: %v\n", err)
	} else {
		fmt.Printf("ID查询成功: ID=%s\n", tuple.ID)
	}

	// 测试条件查询
	conditions := []tuplestore.Condition{
		{ElementIndex: 1, Operator: "=", Value: int32(25)}, // Age = 25
	}
	results, err := store.Query(conditions)
	if err != nil {
		fmt.Printf("条件查询失败: %v\n", err)
	} else {
		fmt.Printf("条件查询成功，找到%d条记录\n", len(results))
		for _, r := range results {
			fmt.Printf("  - ID: %s\n", r.ID)
		}
	}

	// 测试复合条件查询
	conditions = []tuplestore.Condition{
		{ElementIndex: 1, Operator: ">", Value: int32(30)}, // Age > 30
		{ElementIndex: 2, Operator: "=", Value: "Charlie"}, // Name = "Charlie"
	}
	results, err = store.Query(conditions)
	if err != nil {
		fmt.Printf("复合条件查询失败: %v\n", err)
	} else {
		fmt.Printf("复合条件查询成功，找到%d条记录\n", len(results))
		for _, r := range results {
			fmt.Printf("  - ID: %s\n", r.ID)
		}
	}
}
